<template>
  <el-dialog
    v-if="dialogVisible"
    width="500px"
    title="修改密码"
    :lock-scroll="false"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item v-if="isEditSelf" prop="oldPassword" label="旧密码">
        <el-input v-model="form.oldPassword" placeholder="请输入旧密码" onkeyup="value = value.replace(/[\u4E00-\u9FA5]/g,'')" show-password />
      </el-form-item>
      <el-form-item prop="newPassword" label="新密码">
        <el-input v-model="form.newPassword" placeholder="请输入新密码" onkeyup="value = value.replace(/[\u4E00-\u9FA5]/g,'')" show-password>
          <template slot="append">
            <PasswordLevel :password="form.newPassword" @pwdLevel="passwordLevelHandle" />
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { editPassword } from '@/api/user'

export default {
  name: 'EditPassword',
  components: {
    PasswordLevel: () => import('@/views/user/components/PasswordLevel.vue')
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    id: {
      type: Number,
      default: 0
    },
    isEditSelf: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      form: {
        id: this.id,
        passwordLevel: undefined,
        oldPassword: '',
        newPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 50 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          editPassword(this.form).then(res => {
            this.$message.success('修改成功')
            this.handleClose()
          })
        }
      })
    },
    passwordLevelHandle(level) {
      this.form.passwordLevel = level
    },
    handleClose() {
      this.$emit('handleClose')
    }
  }
}
</script>

<style scoped lang="scss">
</style>
